import 'package:cloud_medicine/components/author_show.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/message_api.dart';
import 'package:cloud_medicine/model/dicuss_message_detail.dart';
import 'package:cloud_medicine/pages/image_show.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class DiscussMessageDetailPage extends StatefulWidget {
  final int messageID;
  final int receive;

  DiscussMessageDetailPage({
    Key key,
    @required this.messageID,
    @required this.receive,
  }) : super(key: key);

  @override
  _DiscussMessageDetailPageState createState() =>
      _DiscussMessageDetailPageState();
}

class _DiscussMessageDetailPageState extends State<DiscussMessageDetailPage> {
  bool _loading = false;
  DicussMessageDetailInfo _info;
  int receive;

  @override
  void initState() {
    super.initState();
    _init();
    receive = widget.receive;
  }

  // 初始化，向后端请求数据
  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });
    dynamic res = await getDiscussMessageDetail_api({
      'messageID': widget.messageID,
    });
    if (mounted) {
      setState(() {
        if (res['code'] == 0) {
          _info = DicussMessageDetailInfo.init(res['data']);
        } else {
          errorToast(res['message']);
        }
        _loading = false;
      });
    }
  }

  setReceive(int receiveResult) {
    setState(() {
      receive = receiveResult;
    });
  }

  // 对会诊消息作出应答
  _receive(int result) async {
    setReceive(result);

    dynamic res = await agreeMessage_api({
      'id': widget.messageID,
      'isAgree': result == 1,
    });

    res['code'] == 0
        ? successToast('消息已投递到对方消息中心')
        : errorToast(res['message']);
  }

  Widget showBtns() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        receive == 0
            ? RaisedButton(
                child: Text('同意'),
                color: Colors.green,
                textColor: Colors.white,
                onPressed: () {
                  _receive(1);
                },
              )
            : Container(),
        receive == 0
            ? RaisedButton(
                color: Colors.red,
                textColor: Colors.white,
                child: Text('不同意'),
                onPressed: () {
                  _receive(-1);
                },
              )
            : Container(),
      ],
    );
  }

  // 判断loading并且在loading为false时渲染主要视图
  Widget _childLayout() {
    return _loading
        ? loadingWidget(_loading)
        : ListView(
            children: <Widget>[
              Container(
                color: Colors.white,
                padding: EdgeInsets.all(8),
                child: ListView(
                  shrinkWrap: true, // 为true可以解决子控件必须设置高度的问题
                  physics: NeverScrollableScrollPhysics(), // 禁用滑动事件
                  children: <Widget>[
                    AuthorShow(
                      userID: _info.authorBasicInfo.id,
                      avatar: _info.authorBasicInfo.avatar,
                      realname: _info.authorBasicInfo.realname,
                      createTime: _info.createTime,
                    ),
                    SizedBox(height: 10),
                    Text(_info.content),
                    SizedBox(height: 10),
                    GridView.count(
                      physics: new NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      crossAxisSpacing: 10.0,
                      mainAxisSpacing: 10.0,
                      crossAxisCount: 3,
                      // 一行显示个数
                      childAspectRatio: 1.0,
                      children: getWidgetList(),
                    ),
                    SizedBox(height: 10),
                    showBtns(),
                  ],
                ),
              ),
            ],
          );
  }

  // 生成gridView的网格视图图片
  List<Widget> getWidgetList() {
    return _info.files.map((file) => getItemContainer(file)).toList();
  }

  // 生成每一张图片的样式
  Widget getItemContainer(String file) {
    return GestureDetector(
      child: Container(
        child: FadeInImage.assetNetwork(
          placeholder: 'images/loading.gif', // 占位图
          image: file,
        ),
        color: Colors.grey[100],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => ImageShow(
            url: file,
          ),
        ));
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('会诊消息信息'),
        centerTitle: true,
      ),
      body: _childLayout(),
    );
  }
}
